"""
日志工具类
"""
import logging
import json
import uuid
from datetime import datetime
from typing import Dict, Any, Optional, List
from pythonjsonlogger import jsonlogger
from backend.models.response_models import LogEntry

class LogManager:
    """日志管理器"""
    
    def __init__(self):
        self.logs: List[LogEntry] = []
        self.max_logs = 1000  # 最大保存日志数
        self.logger = self._setup_logger()
        
    def _setup_logger(self) -> logging.Logger:
        """设置日志器"""
        logger = logging.getLogger("kafka_monitor")
        logger.setLevel(logging.INFO)
        
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        
        # 创建JSON格式化器
        json_formatter = jsonlogger.JsonFormatter(
            '%(asctime)s %(name)s %(levelname)s %(message)s'
        )
        console_handler.setFormatter(json_formatter)
        
        # 避免重复添加处理器
        if not logger.handlers:
            logger.addHandler(console_handler)
        
        return logger
    
    def add_log(self, 
                level: str, 
                operation: str, 
                message: str, 
                success: bool = True,
                details: Optional[Dict[str, Any]] = None) -> LogEntry:
        """添加日志条目"""
        log_entry = LogEntry(
            id=str(uuid.uuid4()),
            timestamp=datetime.now(),
            level=level,
            operation=operation,
            message=message,
            success=success,
            details=details
        )
        
        # 添加到内存日志
        self.logs.append(log_entry)
        
        # 保持最大日志数限制
        if len(self.logs) > self.max_logs:
            self.logs = self.logs[-self.max_logs:]
        
        # 记录到系统日志
        log_data = {
            "operation": operation,
            "message": message,
            "success": success,
            "details": details
        }
        
        if level == "ERROR":
            self.logger.error(json.dumps(log_data))
        elif level == "WARNING":
            self.logger.warning(json.dumps(log_data))
        else:
            self.logger.info(json.dumps(log_data))
        
        return log_entry
    
    def get_logs(self, 
                 limit: Optional[int] = None,
                 operation_filter: Optional[str] = None,
                 success_filter: Optional[bool] = None) -> List[LogEntry]:
        """获取日志列表"""
        logs = self.logs.copy()
        
        # 按操作类型过滤
        if operation_filter:
            logs = [log for log in logs if log.operation == operation_filter]
        
        # 按成功状态过滤
        if success_filter is not None:
            logs = [log for log in logs if log.success == success_filter]
        
        # 按时间倒序排列
        logs.sort(key=lambda x: x.timestamp, reverse=True)
        
        # 限制返回数量
        if limit:
            logs = logs[:limit]
        
        return logs
    
    def clear_logs(self):
        """清空日志"""
        self.logs.clear()
        self.logger.info("日志已清空")
    
    def log_connection_test(self, bootstrap_servers: str, success: bool, error: Optional[str] = None):
        """记录连接测试日志"""
        message = f"连接测试{'成功' if success else '失败'}: {bootstrap_servers}"
        details = {"bootstrap_servers": bootstrap_servers}
        if error:
            details["error"] = error
        
        self.add_log(
            level="INFO" if success else "ERROR",
            operation="CONNECTION_TEST",
            message=message,
            success=success,
            details=details
        )
    
    def log_message_send(self, topic: str, success: bool, partition: Optional[int] = None, 
                        offset: Optional[int] = None, error: Optional[str] = None):
        """记录消息发送日志"""
        message = f"消息发送{'成功' if success else '失败'}: {topic}"
        details = {"topic": topic}
        
        if partition is not None:
            details["partition"] = partition
        if offset is not None:
            details["offset"] = offset
        if error:
            details["error"] = error
        
        self.add_log(
            level="INFO" if success else "ERROR",
            operation="SEND_MESSAGE",
            message=message,
            success=success,
            details=details
        )
    
    def log_topic_list(self, topic_count: int, success: bool, error: Optional[str] = None):
        """记录Topic列表获取日志"""
        message = f"获取Topic列表{'成功' if success else '失败'}"
        if success:
            message += f": 共{topic_count}个Topic"
        
        details = {"topic_count": topic_count if success else 0}
        if error:
            details["error"] = error
        
        self.add_log(
            level="INFO" if success else "ERROR",
            operation="GET_TOPICS",
            message=message,
            success=success,
            details=details
        )
    
    def log_operation(self, operation: str, message: str, success: bool = True, 
                     details: Optional[Dict[str, Any]] = None):
        """记录通用操作日志"""
        self.add_log(
            level="INFO" if success else "ERROR",
            operation=operation,
            message=message,
            success=success,
            details=details
        )

# 全局日志管理器实例
log_manager = LogManager() 